package com.sqx.modules.recovery.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sqx.common.utils.Result;
import com.sqx.modules.recovery.dao.GoodsSpecificationsDao;
import com.sqx.modules.recovery.entity.AttributeValue;
import com.sqx.modules.recovery.entity.GoodsSpecifications;
import com.sqx.modules.recovery.service.GoodsSpecificationsService;
import com.sqx.modules.sys.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author Admin
 * @description 针对表【goods_specifications】的数据库操作Service实现
 * @createDate 2024-06-28 10:50:20
 */
@Service
public class GoodsSpecificationsServiceImpl extends ServiceImpl<GoodsSpecificationsDao, GoodsSpecifications>
        implements GoodsSpecificationsService {

    @Override
    public Result saveGoodsSpecifications(GoodsSpecifications goodsSpecifications) {
        SysUserEntity principal = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        if (ObjectUtils.isEmpty(principal)) {
            return Result.error("该用户不存在或未登录");
        }
        // 确保 attributeValue 已经被序列化
        if (goodsSpecifications.getAttributeValueJson() != null) {
            goodsSpecifications.getAttributeValueJson().toString();
            String jsonString = goodsSpecifications.getAttributeValueJson().toString();
            goodsSpecifications.setAttributeValue(jsonString);
        }
        if (goodsSpecifications.getId() != null) {
//            goodsSpecifications.setUpdateBy(principal.getUserId());
            goodsSpecifications.setUpdateTime(new Date());
            return Result.upStatus(baseMapper.updateById(goodsSpecifications));
        } else {
            // 确保 attributeValue 已经被序列化
            if (goodsSpecifications.getAttributeValueJson() != null) {
                goodsSpecifications.getAttributeValueJson().toString();
                String jsonString = goodsSpecifications.getAttributeValueJson().toString();
                goodsSpecifications.setAttributeValue(jsonString);
            }
//            goodsSpecifications.setCreateBy(principal.getUserId());
            goodsSpecifications.setCreateTime(new Date());
            return Result.upStatus(baseMapper.insert(goodsSpecifications));
        }
    }

    @Override
    public Result updateGoodsSpecifications(GoodsSpecifications goodsSpecifications) {
        SysUserEntity principal = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        if (ObjectUtils.isEmpty(principal)) {
            return Result.error("该用户不存在或未登录");
        }
        GoodsSpecifications goodsSpecifications1 = baseMapper.selectById(goodsSpecifications.getId());
        if (goodsSpecifications1 == null) {
            return Result.error("该回收规格不存在");
        }
        // 确保 attributeValue 已经被序列化
        if (goodsSpecifications.getAttributeValueJson() != null) {
            goodsSpecifications.getAttributeValueJson().toString();
            String jsonString = goodsSpecifications.getAttributeValueJson().toString();
            goodsSpecifications.setAttributeValue(jsonString);
        }
//        goodsSpecifications.setUpdateBy(principal.getUserId());
        goodsSpecifications.setUpdateTime(new Date());
        return Result.upStatus(baseMapper.updateById(goodsSpecifications));
    }

    @Override
    public Result deleteGoodsSpecifications(Long id) {
        SysUserEntity principal = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        if (ObjectUtils.isEmpty(principal)) {
            return Result.error("该用户不存在或未登录");
        }
        GoodsSpecifications goodsSpecifications = baseMapper.selectById(id);
        if (goodsSpecifications == null) {
            return Result.error("该回收规格不存在");
        }
        // 检查是否有子项存在
//        List<GoodsSpecifications> childSpecifications = baseMapper.selectChildrenByParentId(id);
//        if (!childSpecifications.isEmpty()) {
//            return Result.error("下级有关联的数据，不能删除");
//        }

        goodsSpecifications.setDeleteFlag(1);
//        goodsSpecifications.setUpdateBy(principal.getUserId());
        goodsSpecifications.setUpdateTime(new Date());
        return Result.upStatus(baseMapper.updateById(goodsSpecifications));
    }

    @Override
    public Result getGoodsSpecificationsList(Integer pageNum, Integer pageSize, Long recoveryId) {
        if (pageNum != null || pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        if (recoveryId != null) {
            List<GoodsSpecifications> list = baseMapper.selectList(new QueryWrapper<GoodsSpecifications>()
                    .eq("recovery_id", recoveryId)
                    .eq("delete_flag", 0));
            // 解析 attributeValue 字段
            for (GoodsSpecifications goodsSpecifications : list) {
                if (goodsSpecifications.getAttributeValue() != null) {
                    String attributeValues = goodsSpecifications.getAttributeValue();
                    // 使用正则表达式修正字符串中的单引号为双引号
                    attributeValues = attributeValues.replaceAll("'", "\"");

                    // 使用正则表达式将等号替换为冒号
                    attributeValues = attributeValues.replaceAll("(?<=[a-zA-Z0-9_])=", ":");

                    List<AttributeValue> attributeValuesList = JSON.parseArray(attributeValues, AttributeValue.class);
                    for (AttributeValue attributeValue : attributeValuesList) {
                        attributeValue.setSpecId(goodsSpecifications.getId().toString());
                    }
                    goodsSpecifications.setAttributes(attributeValuesList);
                }
            }
            return Result.success().put("data", new PageInfo<>(list));
        } else {
            List<GoodsSpecifications> list = baseMapper.selectList(new QueryWrapper<GoodsSpecifications>()
                    .eq("delete_flag", 0));
            // 解析 attributeValue 字段
            for (GoodsSpecifications goodsSpecifications : list) {
                if (goodsSpecifications.getAttributeValue() != null) {
                    String attributeValues = goodsSpecifications.getAttributeValue();
                    // 使用正则表达式修正字符串中的单引号为双引号
                    attributeValues = attributeValues.replaceAll("'", "\"");

                    // 使用正则表达式将等号替换为冒号
                    attributeValues = attributeValues.replaceAll("(?<=[a-zA-Z0-9_])=", ":");

                    List<AttributeValue> attributeValuesList = JSON.parseArray(attributeValues, AttributeValue.class);
                    for (AttributeValue attributeValue : attributeValuesList) {
                        attributeValue.setSpecId(goodsSpecifications.getId().toString());
                    }
                    goodsSpecifications.setAttributes(attributeValuesList);
                }
            }
            return Result.success().put("data", new PageInfo<>(list));
        }
    }

    @Override
    public Result getFirstSpecificationsList(Integer pageNum, Integer pageSize, GoodsSpecifications goodsSpecifications) {
        if (pageNum != null || pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<GoodsSpecifications> list = baseMapper.selectList(new QueryWrapper<GoodsSpecifications>()
                .eq("parent_id", 0)
                .eq("delete_flag", 0));
        return Result.success().put("data", new PageInfo<>(list));
    }

    @Override
    public Result getSecondSpecificationsList(Integer pageNum, Integer pageSize, Long parentId) {
        if (pageNum != null || pageSize != null) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<GoodsSpecifications> list = baseMapper.selectList(new QueryWrapper<GoodsSpecifications>()
                .eq("parent_id", parentId)
                .eq("delete_flag", 0));
        return Result.success().put("data", new PageInfo<>(list));
    }

    @Override
    public Result getGoodsSpecificationsById(Long id) {
        SysUserEntity principal = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        if (ObjectUtils.isEmpty(principal)) {
            return Result.error("该用户不存在或未登录");
        }
        GoodsSpecifications goodsSpecifications = baseMapper.selectById(id);
        if (ObjectUtils.isEmpty(goodsSpecifications)) {
            return Result.error("该回收规格不存在");
        }
        return Result.success().put("data", goodsSpecifications);
    }
}




